<?php

/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2019/11/28
 * Time: 2:02 PM
 */
namespace app\index\controller;

use app\admin\controller\store\Housein;
use app\admin\model\Githouse;
use app\admin\model\halt\Cate;
use app\admin\model\Houseout;
use app\admin\model\Stock;
use app\admin\model\Supplier;
use think\Db;

class Outpur extends Store
{
    public $headUser="ZhangWei";
    public $xsLeader=["WangHaiTao","HuangLiLi","SunGuiPing","LiuQianRan"];
    //销售审核人
    public $xsDocking=["HanXiaoFang","LuYaChao"];
    //销售审核人
    public function _initialize()
    {
        parent::_initialize();
    }
    public function index(){
        //设置权限
        $userid = $this->user['userid'];
        //查询当前所长对接人
        $cidArr=[];
        $docking=array_column(Db::name("githouse")->field('id')->where("find_in_set('".$userid."',docking)")->select(),'id');
        //
        $cids = $this->request->post("cid");

        if ($docking){
            $cidArr = array_merge($cidArr,$docking);

        }
        $sql="";
        $depList = check_Department($this->auth->department,1);
        if($depList){
            $userList = TableListSqlQuery('Admin',"find_in_set('".$depList."',department) and `isleader` = '1'",'userid');

            if (!$userList)return '';
            $leader = $userList[0]['userid'];
            if ($leader==$userid){//是当前领导
                if ($cidArr){
                    $str=implode(",",$cidArr);

                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=$depList";
                    }

                }else{
                    if ($cids!=null) {
                        $sql = "cid=$cids";

                    }else{
                        $sql="sub=$depList";
                    }


                }
                $arr = array_column(Db::name("purout")->field('cid as id')->group("cid")->where(array("sub"=>$depList))->select(),'id');
                $deHouse = Db::name("githouse")->where(array('type'=>0,'dep'=>$depList))->field('id')->find();
                $cidArr=array_merge($cidArr,$arr,array($deHouse['id']));


            }else{

                if ($cidArr){

                    $str=implode(",",$cidArr);
                    if ($cids!=null){
                        $sql="cid=$cids";

                    }else{
                        $sql="cid in ($str) or publisher='{$userid}'";
                    }


                }else{
                    $sql="publisher='{$userid}'";
                }
            }
        }else{
            if ($userid==$this->headUser){
                //如果是总部仓库负责人
                if ($cidArr){

                    $str=implode(",",$cidArr);
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=1";
                    }

                }else{
                    $sql="sub=1";
                }
            }else{
                $sql="publisher='{$userid}'";
            }

        }
        if ($this->request->isAjax()){
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            $info = Db::name("purout")->where($sql)->limit($offset,4)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
                $g=Db::name("githouse")->field("gname")->find($v['cid']);
                $info[$k]['cname']=$g['gname'];
            }

            $result = array("list"=>$info);

            return json($result);

        }

        if ($cidArr){
            $cidArr = array_unique($cidArr);
            $str=implode(",",$cidArr);

            $this->view->assign("arr", Db::name("githouse")->field("gname,id")->where("id in ($str)")->select());


        }else{
            $this->view->assign("arr",[]);
        }
        return $this->view->fetch();
    }

    public function xsindex(){
        //设置权限
        $userid = $this->user['userid'];
        //查询当前所长对接人
        $cidArr=[];
        $docking=array_column(Db::name("githouse")->field('id')->where("find_in_set('".$userid."',docking)")->select(),'id');
        $cids = $this->request->post("cid");
        if ($docking){
            $cidArr = array_merge($cidArr,$docking);
        }
        $sql="";
        $depList = check_Department($this->auth->department,1);
        if($depList){
            $userList = TableListSqlQuery('Admin',"find_in_set('".$depList."',department) and `isleader` = '1'",'userid');
            if (!$userList)return '';
            $leader = $userList[0]['userid'];
            if ($leader==$userid){//是当前领导
                if ($cidArr){
                    $str=implode(",",$cidArr);
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=$depList";
                    }
                }else{
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="sub=$depList";
                    }
                }
                $arr = array_column(Db::name("puroutxs")->field('cid as id')->group("cid")->where(array("sub"=>$depList))->select(),'id');
                $deHouse = Db::name("githouse")->where(array('type'=>0,'dep'=>$depList))->field('id')->find();
                $cidArr=array_merge($cidArr,$arr,array($deHouse['id']));
            }else{
                if ($cidArr){
                    $str=implode(",",$cidArr);
                    if ($cids!=null){
                        $sql="cid=$cids";
                    }else{
                        $sql="cid in ($str) or publisher='{$userid}'";
                    }
                }else{
                    $sql="publisher='{$userid}'";
                }
            }
        }else{
            if ($userid==$this->headUser){
                //如果是总部仓库负责人
                if ($cidArr){

                    $str=implode(",",$cidArr);
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=1";
                    }

                }else{
                    $sql="sub=1";
                }
            }else{
                $sql="publisher='{$userid}'";
            }

        }
        if (!in_array(1,$cidArr)){
            array_unshift($cidArr,1);

        }

        if ($this->request->isAjax()){
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            $info = Db::name("puroutxs")->where($sql)->limit($offset,4)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
                $g=Db::name("githouse")->field("gname")->find($v['cid']);
                $info[$k]['cname']=$g['gname'];
            }

            $result = array("list"=>$info);

            return json($result);

        }

        if ($cidArr){
            $cidArr = array_unique($cidArr);
            $str=implode(",",$cidArr);

            $this->view->assign("arr", Db::name("githouse")->field("gname,id")->where("id in ($str)")->select());


        }else{
            $this->view->assign("arr",[]);
        }
        return $this->view->fetch();
    }


    public function rkindex(){
        //设置权限
        $userid = $this->user['userid'];
        //查询当前所长对接人
        $cidArr=[];
        $docking=array_column(Db::name("githouse")->field('id')->where("find_in_set('".$userid."',docking)")->select(),'id');
        $cids = $this->request->post("cid");
        if ($docking){
            $cidArr = array_merge($cidArr,$docking);
        }
        $sql="";
        $depList = check_Department($this->auth->department,1);
        if($depList){
            $userList = TableListSqlQuery('Admin',"find_in_set('".$depList."',department) and `isleader` = '1'",'userid');
            if (!$userList)return '';
            $leader = $userList[0]['userid'];
            if ($leader==$userid){//是当前领导
                if ($cidArr){
                    $str=implode(",",$cidArr);
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=$depList";
                    }
                }else{
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="sub=$depList";
                    }
                }
                $arr = array_column(Db::name("purout")->field('cid as id')->group("cid")->where(array("sub"=>$depList))->select(),'id');
                $deHouse = Db::name("githouse")->where(array('type'=>0,'dep'=>$depList))->field('id')->find();
                $cidArr=array_merge($cidArr,$arr,array($deHouse['id']));
            }else{
                if ($cidArr){
                    $str=implode(",",$cidArr);
                    if ($cids!=null){
                        $sql="cid=$cids";
                    }else{
                        $sql="cid in ($str) or publisher='{$userid}'";
                    }
                }else{
                    $sql="publisher='{$userid}'";
                }
            }
        }else{
            if ($userid==$this->headUser){
                //如果是总部仓库负责人
                if ($cidArr){

                    $str=implode(",",$cidArr);
                    if ($cids!=null) {
                        $sql = "cid=$cids";
                    }else{
                        $sql="cid in ($str) or sub=1";
                    }

                }else{
                    $sql="sub=1";
                }
            }else{
                $sql="publisher='{$userid}'";
            }

        }
        if ($this->request->isAjax()){
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            $info = Db::name("purin")->where($sql)->limit($offset,4)->order("id desc")->select();
            foreach ($info as $k=>$v){
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
                $g=Db::name("githouse")->field("gname")->find($v['cid']);
                $info[$k]['cname']=$g['gname'];
            }

            $result = array("list"=>$info);

            return json($result);

        }

        if ($cidArr){
            $cidArr = array_unique($cidArr);
            $str=implode(",",$cidArr);

            $this->view->assign("arr", Db::name("githouse")->field("gname,id")->where("id in ($str)")->select());


        }else{
            $this->view->assign("arr",[]);
        }
        return $this->view->fetch();
    }

    //获取所属分公司
    protected function getSub($cid){
        $ginfo = Db::name("githouse")->find($cid);
        if (!$ginfo)return false;
        if ($cid==1)return 1;
        //仓库管理人
        $manger=$ginfo['manger'];
        if ($ginfo['type']==0){
            $dep=$ginfo['dep'];
            return $dep;
        }else{
            $uadmin = Db::name("admin")->where(array("userid"=>$ginfo['manger']))->field('department')->find();
            if (!$uadmin)return false;
            $this->auth->department = $uadmin['department'];
            $depList = check_Department($this->auth->department,1);//当前所在公司
            if (!$depList){
                return 1;
            }else{
               return $depList;

            }
        }

    }
    //销售出库编辑
    public function xsedit($id){
        $house = $this->getXsCk();
        $info = Db::name("puroutxs")->where(array('id'=>$id))->find();
        if ($info==null)$this->error("订单不存在");
        if ($info['status']==10 || $info['status']==5 || $info['publisher']!=$this->user['userid']) {
            if ($this->request->isAjax() && $this->request->isPost()){
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['shopList']);
                $leader = $this->getShangji($post['cid']);
                if (!$leader)$this->error("请联系上级");
                $this->checkXsStore($shopList,$post['cid']);

                $post['sub']=$this->getSub($post['cid']);
                Db::name("puroutxs")->where(array("id"=>$id))->update($post);
                Db::name('puroutxs_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('puroutxs_data')->insert(array('shopid'=>$v['id'],'zhekou'=>$v['zhekou'],'num'=>$v['num'],'pur_id'=>$id));
                }
                if ($post['status']==9){
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有销售单需要审核，请前往处理</div>",$this->host."index/outpur/xsview/id/".$id,$leader);

                }
                $this->setWork($info,$post['status'],6);

                $this->success("编辑成功","/index/outpur/view2/id/".$id);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

            $ginfo = Db::name("githouse")->where(array("id"=>$info['cid']))->find();
            $this->view->assign('ginfo',$ginfo);
            $this->view->assign('info',$info);
            foreach ($house as $k=>$v) {
                $house[$k]['store']=$this->getCurStore($v['id']);
            }
            $this->view->assign('house',$house);
            $this->view->assign("username",$this->user['username']);
            $purList=Db::name('puroutxs_data')->field('shopid as id,num,zhekou')->where(array("pur_id"=>$id))->select();

            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['type']="成品";

                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStoreNum($info['cid'],$v['id']);
            }
            if (count($house) > 1){
                $this->view->assign("st",0);
            }else{
                $this->view->assign("st",1);
            }
            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }else{
            $this->error("当前单号不能编辑","/index/Outpur/xsview/id/".$id);

        }


    }

    //入库单编辑
    public function edit2($id){
        $house = $this->getHouse();
        $info = Db::name("purin")->where(array('id'=>$id))->find();
        if ($info==null)$this->error("订单不存在");
        if ($info['status']==10 || $info['status']==5 || $info['publisher']!=$this->user['userid']) {
            if ($this->request->isAjax() && $this->request->isPost()){
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['shopList']);
                $leader = $this->getShangji($post['cid']);
                if (!$leader)$this->error("请联系上级");
                $post['sub']=$this->getSub($post['cid']);
                Db::name("purin")->where(array("id"=>$id))->update($post);
                Db::name('purin_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('purin_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'pur_id'=>$id));
                }
                if ($post['status']==9){
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($this->user['userid']).".有入库单需要审核，请前往处理</div>",$this->host."index/outpur/view2/id/".$id,$leader);

                }
                $this->setWork($info,$post['status'],5);

                $this->success("编辑成功","/index/outpur/view2/id/".$id);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

            $ginfo = Db::name("githouse")->where(array("id"=>$info['cid']))->find();
            $this->view->assign('ginfo',$ginfo);
            $this->view->assign('info',$info);
            foreach ($house as $k=>$v) {
                $house[$k]['store']=$this->getCurStore($v['id']);
            }
            $this->view->assign('house',$house);
            $this->view->assign("username",$this->user['username']);
            $purList=Db::name('purin_data')->field('shopid as id,num')->where(array("pur_id"=>$id))->select();

            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['type']=$this->getType($v['id']);
                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStoreNum($info['cid'],$v['id']);
            }
            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }else{
            $this->error("当前单号不能编辑","/index/Outpur/view/id/".$id);

        }


    }


    public function edit($id){
        $house = $this->getHouse();
        $info = Db::name("purout")->where(array('id'=>$id))->find();
        if ($info==null)$this->error("订单不存在");
        if ($info['status']==10 || $info['status']==5 || $info['publisher']!=$this->user['userid']) {
            if ($this->request->isAjax() && $this->request->isPost()){
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['shopList'],$post['sub']);
                $this->checkStore($shopList,$post['cid']);
                //检测库存是否充足
                $leader = $this->getShangji($post['cid']);
                if (!$leader)$this->error("请联系上级");
                $post['sub']=$this->getSub($post['cid']);

                Db::name("purout")->where(array("id"=>$id))->update($post);
                Db::name('purout_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('purout_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'pur_id'=>$id));
                }
                if ($post['status']==9){
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($this->user['userid']).".有出库单需要审核，请前往处理</div>",$this->host."index/outpur/view/id/".$pid,$leader);

                }
                $this->setWork($info,$post['status']);

                $this->success("编辑成功","/index/outpur/view/id/".$id);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);

            $ginfo = Db::name("githouse")->where(array("id"=>$info['cid']))->find();
            $this->view->assign('ginfo',$ginfo);
            $this->view->assign('info',$info);
            foreach ($house as $k=>$v) {
                $house[$k]['store']=$this->getCurStore($v['id']);
            }
            $this->view->assign('house',$house);
            $this->view->assign("username",$this->user['username']);
            $purList=Db::name('purout_data')->field('shopid as id,num')->where(array("pur_id"=>$id))->select();

            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['type']=$this->getType($v['id']);
                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStoreNum($info['cid'],$v['id']);
            }
            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }else{
            $this->error("当前单号不能编辑","/index/Outpur/view/id/".$id);

        }


    }
    //获取上级
    protected function getShangji($cid){
        $ginfo = Db::name("githouse")->find($cid);

        if (!$ginfo)return false;
        if ($cid==1)return $this->headUser;
        //仓库管理人
        $manger=$ginfo['manger'];
        if ($ginfo['type']==0){
            $dep=$ginfo['dep'];
            $userList = TableListSqlQuery('Admin',"find_in_set('".$dep."',department) and `isleader` = '1'",'userid');
            $leader = $userList[0]['userid'];

        }else{
            $uadmin = Db::name("admin")->where(array("userid"=>$ginfo['manger']))->field('department')->find();
            $this->auth->department=$uadmin['department'];
            $depList = check_Department($this->auth->department,1);//当前所在公司

            if (!$depList){

                return $this->headUser;


            }else{
                $userList = TableListSqlQuery('Admin',"find_in_set('".$depList."',department) and `isleader` = '1'",'userid');
                if (!$userList)return false;
                $leader = $userList[0]['userid'];
                //$leader=$this->headUser;//总部上级人，上线删除


            }
        }
        return $leader;

    }
    //入库单
    function xsview($id){
        $info = Db::name("puroutxs")->find($id);
        if (!$info)$this->error('参数错误');
        $info['username']=$this->getPublisher($info['publisher']);
        $this->view->assign("userArr",[]);
        $stepArr2=[9,8,7,6,-6];//审核级别
        if (in_array($info['status'],$stepArr2)){
            $info['status_text'] = '<span class="num_right shenpi">待审批</span>';

        }else{
            $info['status_text'] = $this->getStatus($info['status']);
        }

        //获取当前仓库管理人，分公司负责人
        $cid = $info['cid'];
        $leader = $this->getShangji($cid);
        if (!$leader)$this->error("请联系当前所属分公司");
        $userid = $this->user['userid'];
        $ginfo = Db::name("githouse")->field('docking')->find($cid);
        $docking = explode(',',$ginfo['docking']);
        //1自身，2分公司分公司负责人3审核人，4当前仓库对接人，5 销售对接人
        if ($info['publisher']!=$userid && $leader!=$userid && !in_array($userid,$this->xsLeader) && !in_array($userid,$docking) && !in_array($userid,$this->xsDocking)){
            $this->error("无权限访问");
        }
        $info['cidName']=$this->getCid($info['cid']);
        //审核数组
        $stepArr=[$leader];//所有审核人放一起
        foreach ($this->xsLeader as $v){
            array_push($stepArr,$v);
        }

        $worklist=[];
        $person=0;
        //该谁审核
        $pos = array_search($info['status'],$stepArr2);

        $person=$stepArr[$pos];

        if ($info['status']!=10){
            $worklist = Db::name("puroutxs_work")->where(array("pid" => $id))->select();
            if ($worklist) {
                foreach ($worklist as $k => $v) {
                    $worklist[$k]['user'] = $this->getInfo($v['publisher']);
                }
            }
            if (in_array($info['status'],$stepArr2)){
                $leadInfo=array(
                    'status'=>3,
                    "user"=>$this->getInfo($person),
                    'mark'=>''
                );
                array_push($worklist,$leadInfo);
            }
        }
        $this->view->assign('worklist',$worklist);
        $this->view->assign("info",$info);
        $this->view->assign("userid",$this->user['userid']);
        $this->view->assign("leader",$leader);
        $list = Db::name('puroutxs_data')->field("shopid,num,zhekou")->where(array('pur_id' => $id))->select();
        foreach ($list as $k=>$v){
            $list[$k]['cname']=$this->getCname($v['shopid']);
        }
//        switch ($status){
//            case 9:
//                break;
//        }
        $this->view->assign("person",$person);

        $this->view->assign("list",$list);
        return $this->view->fetch();
    }

    //入库单
    function view2($id){
        $info = Db::name("purin")->find($id);
        if (!$info)$this->error('参数错误');
        $info['username']=$this->getPublisher($info['publisher']);
        $this->view->assign("userArr",[]);
        $info['status_text'] = $this->getStatus($info['status']);

        //获取当前仓库管理人，分公司负责人
        $cid = $info['cid'];
        $leader = $this->getShangji($cid);
        if (!$leader)$this->error("请联系当前所属分公司");
        $userid = $this->user['userid'];
        $ginfo = Db::name("githouse")->field('docking')->find($cid);
        $docking = explode(',',$ginfo['docking']);
        if ($info['publisher']!=$userid && !in_array($userid,$docking) && $userid!=$leader){//不是领导
            $this->error("无权限访问");
        }
        $info['cidName']=$this->getCid($info['cid']);
        $worklist=[];
        if ($info['status']!=10){
            $worklist = Db::name("purin_work")->where(array("pid" => $id))->select();
            if ($worklist) {
                foreach ($worklist as $k => $v) {
                    $worklist[$k]['user'] = $this->getInfo($v['publisher']);
                }
            }
            if ($info['status']==9){

                $leadInfo=array(
                    'status'=>3,
                    "user"=>$this->getInfo($leader),
                    'mark'=>''
                );
                array_push($worklist,$leadInfo);
            }

        }

        $this->view->assign('worklist',$worklist);


        $this->view->assign("info",$info);



        $this->view->assign("userid",$this->user['userid']);
        $this->view->assign("leader",$leader);

        $list = Db::name('purin_data')->field("shopid,num")->where(array('pur_id' => $id))->select();
        foreach ($list as $k=>$v){
            $list[$k]['cname']=$this->getCname($v['shopid']);
            $list[$k]['types']=$this->getType($v['shopid']);

        }

        $this->view->assign("list",$list);

        return $this->view->fetch();
    }
    function view($id){
        $info = Db::name("purout")->find($id);
        if (!$info)$this->error('参数错误');
        $info['username']=$this->getPublisher($info['publisher']);
        $this->view->assign("userArr",[]);
        $info['status_text'] = $this->getStatus($info['status']);

        //获取当前仓库管理人，分公司负责人
        $cid = $info['cid'];
        $leader = $this->getShangji($cid);
        if (!$leader)$this->error("请联系当前所属分公司");
        $userid = $this->user['userid'];
        $ginfo = Db::name("githouse")->field('docking')->find($cid);
        $docking = explode(',',$ginfo['docking']);
        if ($info['publisher']!=$userid && !in_array($userid,$docking) && $userid!=$leader){//不是领导
            $this->error("无权限访问");
        }
        $info['cidName']=$this->getCid($info['cid']);
        $worklist=[];
        if ($info['status']!=10){
            $worklist = Db::name("purout_work")->where(array("pid" => $id))->select();
            if ($worklist) {
                foreach ($worklist as $k => $v) {
                    $worklist[$k]['user'] = $this->getInfo($v['publisher']);
                }
            }
            if ($info['status']==9){

                $leadInfo=array(
                    'status'=>3,
                    "user"=>$this->getInfo($leader),
                    'mark'=>''
                );
                array_push($worklist,$leadInfo);
            }

        }

        $this->view->assign('worklist',$worklist);


        $this->view->assign("info",$info);



        $this->view->assign("userid",$this->user['userid']);
        $this->view->assign("leader",$leader);

        $list = Db::name('purout_data')->field("shopid,num")->where(array('pur_id' => $id))->select();
        foreach ($list as $k=>$v){
            $list[$k]['cname']=$this->getCname($v['shopid']);
            $list[$k]['types']=$this->getType($v['shopid']);

        }

        $this->view->assign("list",$list);

        return $this->view->fetch();
    }
    protected function getCid($cid){
        $info = Db::name('githouse')->field('gname')->find($cid);
        if (!$info)return '';
        return $info['gname'];

    }

    public function oper3(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }

        $userid = $this->user['userid'];
        $info = Db::name('puroutxs')->where(array('id'=>$id))->find();
        $leader=$this->getShangji($info['cid']);
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        //检查权限
        switch ($status){
            case 10:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                //检查权限
                Db::name("puroutxs")->where(array("id"=>$id))->update(array("status"=>9));
                $this->setWork($info,9);
                $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有销售单需要审核，请前往处理</div>",$this->host."index/outpur/xsview/id/".$id,$leader);

                $this->success("操作成功");
                break;
            case 9:
                //审核通过
                $this->shenhe5($info,$status);
                break;
            case 8:
                //审核通过
                $this->shenhe5($info,$status);
                break;
            case 7:
                //审核通过
                $this->shenhe5($info,$status);
                break;
            case 6:
                //审核通过
                $this->shenhe5($info,$status);
                break;
            case -6:
                //审核通过
                $this->shenhe5($info,$status);
                break;
            case 5:

                if ($info['publisher']!=$userid)$this->error("您没有权限");
                Db::name("puroutxs")->where(array('id'=>$id))->update(array("status"=>4));
                $this->setWork($info,4,6);
                $this->success("操作成功");
                break;

        }
    }
    //审核操作，5步
    public function shenhe5($info,$status){
        if(!$info)$this->error("操作失败");
        $stepArr2=[9,8,7,6,-6];//审核级别
        if (!in_array($info['status'],$stepArr2))$this->error("操作失败");
        $leader = $this->getShangji($info['cid']);
        $arr=array($leader);
        foreach ($this->xsLeader as $v){
            array_push($arr,$v);
        }
        $manger = $arr[array_search($status,$stepArr2)];
        if ($manger!=$this->user['userid'])$this->error("没有权限");

        if ($status==-6){
            $setStatus=1;
        }else{
            //移动位置
            $setStatus = $stepArr2[array_search($status,$stepArr2)+1];
        }
       //库存不充足，是否能审核通过
           $arrData = Db::name("puroutxs_data")->where(array("pur_id"=>$info['id']))->field("shopid as id,num")->select();
           $this->checkXsStore($arrData,$info['cid']);
           Db::name("puroutxs")->where(array("id"=>$info['id']))->update(array("status"=>$setStatus));
           Db::name("puroutxs_work")->insert(array(
                "pid"=>$info['id'],
                "inputtime"=>time(),
                "publisher"=>$this->user['userid'],
                "mark"=>'',
                "status"=>1
            ));
        $this->setWork($info,$setStatus,6);
        $cid = $info['cid'];

        if ($setStatus==1){

            $this->sendText("待审核通知","<div class=\"gray\">你的销售单已通过审核，请前往查看</div>",$this->host."index/outpur/xsview/id/".$info['id'],$info['publisher']);
            $d = Db::name("githouse")->field('docking')->find($cid);
            $dock = $d['docking'];
            $dockAll =  implode("|",array_merge($this->xsDocking,explode(",",$dock)));

            $this->sendText("操送通知","<div class=\"gray\">".$this->getPublisher($info['publisher'])."的销售单已通过审核，请前往查看</div>",$this->host."index/outpur/xsview/id/".$info['id'],$info['publisher']);

        }else{
            $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有销售单需要审核，请前往处理</div>",$this->host."index/outpur/xsview/id/".$info['id'],$leader);

        }
        if ($setStatus==1){
            //
            $outDb=new Houseout();
            $order_id = $outDb->getOrderId();
            if ($cid==1){

                $shopArr=array();//所有半成品id，压榨入库
                foreach ($arrData as $k=>$v){
                    $infos = Db::name("preproduct")->where(array("id"=>$v['id']))->field('id,type,bcp')->find();
                    $bcp = $infos['bcp'];
                    $num=$v['num'];
                    $bcp = explode(",",$bcp);
                    foreach ($bcp as $d){
                        if (!array_key_exists($d,$shopArr)){
                            $shopArr["a_".$d]=$num;
                        }else{
                            $shopArr["a_".$d]+=$num;
                        }
                    }
                }

                //减少库存
                foreach ($shopArr as $key=>$val){
                    $key=intval(substr($key,2));
                    Db::name("stock")->where(array('cid'=>$cid,"shopid"=>$key))->setDec('num',$val);
                    $arr=array(
                        "order_id"=>$order_id,
                        'type'=>5,
                        'shopid'=>$key,
                        'num'=>$val,
                        'cid'=>$cid,
                        'pur_id'=>$info['id'],
                        'inputtime'=>time(),
                        'publisher'=>$info['publisher'],
                        'mark'=>"销售出库",
                        "bcp"=>''

                    );
                   $outDb->insert($arr);
                }


            }else{
                foreach ($arrData as $k=>$v){
                    Db::name("stock")->where(array('cid'=>$cid,"shopid"=>$v['id']))->setDec('num',$v['num']);
                    $arr=array(
                        "order_id"=>$order_id,
                        'type'=>5,
                        'shopid'=>$v['id'],
                        'num'=>$v['num'],
                        'cid'=>$cid,
                        'pur_id'=>$info['id'],
                        'inputtime'=>time(),
                        'publisher'=>$info['publisher'],
                        'mark'=>"销售出库",
                        "bcp"=>''
                    );
                    $outDb->insert($arr);
                }

             }
       }
        $this->success("操作成功");

    }
    public function oper2(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }

        $userid = $this->user['userid'];
        $info = Db::name('purin')->where(array('id'=>$id))->find();

        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        //检查权限
        $leader = $this->getShangji($info['cid']);
        if (!$leader)$this->error('请联系当前分公司管理负责人');
        if ($leader!=$userid && $status!=10 && $status!=5)$this->error("您没有权限");
        switch ($status){
            case 10:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                //检查权限
                Db::name("purin")->where(array("id"=>$id))->update(array("status"=>9));
                $this->setWork($info,9);
                $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($info['publisher']).".有入库单需要审核，请前往处理</div>",$this->host."index/outpur/view2/id/".$info['id'],$leader);

                $this->success("操作成功");
                break;
            case 9:
                //审核通过
                $data = Db::name("purin_data")->field("shopid as id,num")->where(array("pur_id"=>$id))->select();
                Db::name("purin")->where(array("id"=>$id))->update(array("status"=>1));
                Db::name("purin_work")->insert(array(
                    "pid"=>$id,
                    "inputtime"=>time(),
                    "publisher"=>$userid,
                    "mark"=>'',
                    "status"=>1
                ));

                $this->setWork($info,1,5);
                $inDb = new \app\admin\model\house\In();
                $order_id = $inDb->getOrderId();
                $typeArr=[0,3,7];
                //exit;
                foreach ($data as $v){
                    $arr = array(
                        'order_id'=>$order_id,
                        'type'=>$typeArr[$info['type']],
                        'shopid'=>$v['id'],
                        'num'=>$v['num'],
                        'cid'=>$info['cid'],
                        'pur_id'=>$id,
                        'inputtime'=>time(),
                        "publisher"=>$info['publisher'],
                        'mark'=>'入库',
                        'bcp'=>'',

                    );
                    if (Db::name('stock')->where(array("shopid"=>$v['id'],'cid'=>$info['cid']))->find()){
                        Db::name('stock')->where(array("shopid"=>$v['id'],'cid'=>$info['cid']))->setIn('num',$v['num']);
                    }else{
                        $types = $this->getType($v['id'])=="成品" ? 2 : 1;
                        Db::name('stock')->insert(array("shopid"=>$v['id'],'cid'=>$info['cid'],'num'=>$v['num'],'type'=>$types));
                    }
                    $inDb->insert($arr);
                }
                $this->sendText("审核成功","<div class=\"gray\">订单已经通过审核</div>",$this->host."index/outpur/view2/id/".$info['id'],$info['publisher']);
                $docking = Db::name("githouse")->field('docking')->find($info['cid']);
                $this->sendText("操送通知","<div class=\"gray\">有新的入库单</div>",$this->host."index/outpur/view2/id/".$info['id'],str_replace(",","|",$docking['docking']));

                $this->success("操作成功");
                break;

            case 5:

                if ($info['publisher']!=$userid)$this->error("您没有权限");

                Db::name("purin")->where(array('id'=>$id))->update(array("status"=>4));
                $this->setWork($info,4,5);
                $this->success("操作成功");
                break;

        }
    }

    public function oper(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }

        $userid = $this->user['userid'];
        $info = Db::name('purout')->where(array('id'=>$id))->find();

        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        //检查权限
        $leader = $this->getShangji($info['cid']);
        if (!$leader)$this->error('请联系当前分公司管理负责人');
        if ($leader!=$userid && $status!=10 && $status!=5)$this->error("您没有权限");
        switch ($status){
            case 10:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                //检查权限
                Db::name("purout")->where(array("id"=>$id))->update(array("status"=>9));
                $this->sendText("审核成功","<div class=\"gray\">订单已经通过审核</div>",$this->host."index/outpur/view/id/".$info['id'],$leader);

                $this->setWork($info,9);
                $this->success("操作成功");
                break;
            case 9:
                //审核通过
                //检测当前订单库存是否还充足
                $data = Db::name("purout_data")->field("shopid as id,num")->where(array("pur_id"=>$id))->select();
                $this->checkStore($data,$info['cid']);
                Db::name("purout")->where(array("id"=>$id))->update(array("status"=>1));


                Db::name("purout_work")->insert(array(
                    "pid"=>$id,
                    "inputtime"=>time(),
                    "publisher"=>$userid,
                    "mark"=>'',
                    "status"=>1
                ));
                $this->setWork($info,1);
                $outDb = new Houseout();
                $order_id = $outDb->getOrderId();
                $typeArr=[6,6,6];
                //exit;
                foreach ($data as $v){
                    $arr = array(
                        'order_id'=>$order_id,
                        'type'=>$typeArr[$info['type']],
                        'shopid'=>$v['id'],
                        'num'=>$v['num'],
                        'cid'=>$info['cid'],
                        'pur_id'=>$id,
                        'inputtime'=>time(),
                        "publisher"=>$info['publisher'],
                        'mark'=>'出库',
                        'bcp'=>'',

                    );
                    Db::name('stock')->where(array("shopid"=>$v['id'],'cid'=>$info['cid']))->setDec('num',$v['num']);
                    $outDb->insert($arr);
                }
                $this->sendText("审核成功","<div class=\"gray\">订单已经通过审核</div>",$this->host."index/outpur/view/id/".$info['id'],$info['publisher']);
                $docking = Db::name("githouse")->field('docking')->find($info['cid']);
                $this->sendText("操送通知","<div class=\"gray\">有新的出库单</div>",$this->host."index/outpur/view/id/".$info['id'],str_replace(",","|",$docking['docking']));

                $this->success("操作成功");
                break;

            case 5:
                if ($info['publisher']!=$userid)$this->error("您没有权限");

                Db::name("purout")->where(array('id'=>$id))->update(array("status"=>4));
                $this->setWork($info,4);
                $this->success("操作成功");
                break;

        }
    }
    //驳回
    function reject3(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $mark = $this->request->post("mark");
        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $info = Db::name('puroutxs')->where(array('id'=>$id))->find();
        $status = $info['status'];

        $stepArr2=[9,8,7,6,-6];//审核级别
        if (!in_array($info['status'],$stepArr2))$this->error("操作失败");
        $leader = $this->getShangji($info['cid']);
        $arr=array($leader);
        foreach ($this->xsLeader as $v){
            array_push($arr,$v);
        }
        $manger = $arr[array_search($status,$stepArr2)];
        if ($manger!=$this->user['userid'])$this->error("没有权限");
        DB::name("puroutxs")->where(array("id"=>$id))->update(array("status"=>5));
        DB::name("puroutxs_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$this->user['userid'],
            "mark"=>$mark,
            "status"=>2
        ));
        $this->setWork($info,5,6);
        $this->sendText("驳回通知","<div class=\"gray\">入库单已被驳回\n原因：{$mark}</div>",$this->host."index/outpur/xsview/id/".$info['id'],$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");



    }



    //驳回
    function reject2(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $mark = $this->request->post("mark");
        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $info = Db::name('purin')->where(array('id'=>$id))->find();
        $leader = $this->getShangji($info['cid']);
        if (!$leader)$this->error("请联系当前所属分公司");
        $userid = $this->user['userid'];
        if ($leader!=$userid)$this->error("请联系当前所属公司");
        DB::name("purin")->where(array("id"=>$id))->update(array("status"=>5));
        DB::name("purin_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>$mark,
            "status"=>2
        ));
        $this->setWork($info,5,5);
        $this->sendText("驳回通知","<div class=\"gray\">入库单已被驳回\n原因：{$mark}</div>",$this->host."index/outpur/view2/id/".$info['id'],$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");



    }

    //驳回
    function reject(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $mark = $this->request->post("mark");
        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $info = Db::name('purout')->where(array('id'=>$id))->find();
        $leader = $this->getShangji($info['cid']);
        if (!$leader)$this->error("请联系当前所属分公司");
        $userid = $this->user['userid'];
        if ($leader!=$userid)$this->error("请联系当前所属公司");
        DB::name("purout")->where(array("id"=>$id))->update(array("status"=>5));
        DB::name("purout_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>$mark,
            "status"=>2
        ));
        $this->setWork($info,5);
        $this->sendText("驳回通知","<div class=\"gray\">出库单已被驳回\n原因：{$mark}</div>",$this->host."index/outpur/view/id/".$info['id'],$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");



    }
    //检查销售单仓库是否充足

    protected function checkXsStore($arr,$cid){
        if (!$arr || !$cid)$this->error("参数错误");
        $temp=0;
        if (!$arr)$this->error("请选择产品");
        if ($cid==1){
            $preDb = new \app\admin\model\Preproduct();
            $shopArr=array();//所有半成品id，压榨入库
            foreach ($arr as $k=>$v){
                $info = $preDb->where(array("id"=>$v['id']))->field('id,type,bcp')->find();
                $bcp = $info['bcp'];
                $num=$v['num'];
                $bcp = explode(",",$bcp);
                foreach ($bcp as $d){
                    if (!array_key_exists($d,$shopArr)){
                        $shopArr["a_".$d]=$num;
                    }else{
                        $shopArr["a_".$d]+=$num;
                    }
                }
            }
            $tempStatus=[];

            //检测库存
            foreach ($shopArr as $key=>$val){
                $key=intval(substr($key,2));

                $info = Db::name("stock")->where(array('cid'=>$cid,"shopid"=>$key))->find();
                if (!$info){
                    $tempStatus=array("status"=>0,"id"=>$key);
                    break;
                }
                if ($info['num'] < $val){
                    $tempStatus=array("status"=>0,"id"=>$key);
                    break;
                }
            }
            if ($tempStatus){
                $this->error($this->getCname($tempStatus['id'])."库存不足");
            }

            return true;

        }
        $db = new Stock();
        foreach ($arr as $v){
            $st = $db->where(array("cid"=>$cid,"shopid"=>$v['id']))->find();
            if (!$st || $st['num'] < $v['num']){
                $temp=$v['id'];
                break;
            }
        }
        if ($temp > 0)$this->error($this->getCname($temp)."库存不足");
        return true;
    }
    //检查单个仓库库存是否充足

    protected function checkStore($arr,$cid){
        if (!$arr || !$cid)$this->error("参数错误");
        $temp=0;
        $db = new Stock();
        foreach ($arr as $v){
           $st = $db->where(array("cid"=>$cid,"shopid"=>$v['id']))->find();

           if (!$st || $st['num'] < $v['num']){
               $temp=$v['id'];
               break;
           }
        }
        if ($temp > 0)$this->error($this->getCname($temp)."库存不足");

        return true;
    }
    protected function getStoreNum($cid,$id){
        if (!$cid || !$id)return 0;
        $info = Db::name("stock")->where(array("cid"=>$cid,"shopid"=>$id))->find();
        if ($info)return $info['num'];
        return 0;
    }
    //当前产品半成品和成品
    protected function getType($id){
        if (!$id)return false;
        $info = Db::name("preproduct")->field('type')->where(array('id'=>$id))->find();
        if (!$info)return'';
        if ($info['type']==2)return "成品";
        return "半成品";

    }
    public function rkadd(){
        $house = $this->getHouse();
        if ($this->request->isPost() && isset($_POST['sub'])) {
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            unset($post['riqi'],$post['shopList'],$post['sub']);
            //找到上级
            $leader = $this->getShangji($post['cid']);
            if (!$leader)$this->error("请联系所属公司管理员");
            //$this->checkStore($shopList,$post['cid']);
            $post['sub']=$this->getSub($post['cid']);
            $pid = Db::name("purin")->insert($post,0,1);
            if (!$pid) {
                Db::rollback();
                $this->error("订单号重复");
            }
            foreach ($shopList as $k=>$v){
                $check=Db::name('purin_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'pur_id'=>$pid));
                if (!$check)break;
            }
            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{
                if ($post['status']==9){
                    //发送推送通知
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($post['publisher']).".有入库单需要审核，请前往处理</div>",$this->host."index/outpur/view2/id/".$pid,$leader);

                }
                $this->setWork(Db::name("purin")->where(array("id"=>$pid))->find(),$post['status'],5);
                $this->success("添加成功");
            }

        }else{
            //获取当前仓库权限，并选择产品
            foreach ($house as $k=>$v) {
                $house[$k]['store']=$this->getCurStore($v['id']);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);


            $this->view->assign("house",$house);
            $this->view->assign("username",$this->user['username']);
            if (count($house) > 1){
                $this->view->assign("st",0);
            }else{
                $this->view->assign("st",1);

            }
            $this->view->assign("bh",date("Ymd").substr(time(),6).random(4,1));
            //check_Department($this=2);

            return $this->view->fetch();
        }
    }
    //销售出库
    public function xsadd(){
        $house = $this->getXsCk();
        if ($this->request->isPost() && isset($_POST['sub'])) {
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            unset($post['riqi'],$post['shopList'],$post['sub']);
            //找到上级
            $leader = $this->getShangji($post['cid']);
            if (!$leader)$this->error("请联系所属公司管理员");
            $this->checkXsStore($shopList,$post['cid']);
            $post['sub']=$this->getSub($post['cid']);
            $pid = Db::name("puroutxs")->insert($post,0,1);
            if (!$pid) {
                Db::rollback();
                $this->error("订单号重复");
            }
            foreach ($shopList as $k=>$v){
                $check=Db::name('puroutxs_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'zhekou'=>$v['zhekou'],'pur_id'=>$pid));
                if (!$check)break;
            }
            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{
                if ($post['status']==9){
                    //发送推送通知
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($post['publisher']).".有销售单需要审核，请前往处理</div>",$this->host."index/outpur/xsview/id/".$pid,$leader);

                }
                $this->setWork(Db::name("puroutxs")->where(array("id"=>$pid))->find(),$post['status'],6);
                $this->success("添加成功");
            }
        }else{
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();

            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);
            $this->view->assign("house",$house);
            $this->view->assign("username",$this->user['username']);
            if (count($house) > 1){
                $this->view->assign("st",0);
            }else{
                $this->view->assign("st",1);
            }
            $this->view->assign("bh",date("Ymd").substr(time(),6).random(4,1));
            return $this->view->fetch();
        }

    }
    //获取销售仓库
    protected function getXsCk(){
        $userid = $this->user['userid'];
        //获取当前所属分公司
        $leader = check_Department($this->auth->department,1);
        $arr=[];

        if (!$leader){
            //查询是否是总部图书经理，并且是个人仓库
            $person = Db::name("githouse")->where(array("manger"=>$userid,'type'=>1))->find();
            if ($person && $person['id']!=1){//总部负责人
                    //如果属于总部，又有自己的仓库
                    $arr=array(array("id"=>$person['id'],"gname"=>$person['gname']));
            }
        }else{
            //分公司是否有自己仓库
            $person = Db::name("githouse")->where(array("manger"=>$userid,'type'=>1))->find();

            if ($person && $person['id']!=1){
                //个人仓库
                $arr=array(array("id"=>$person['id'],"gname"=>$person['gname']));

            }else{
                //找到当前分公司所存在的仓库
                $depHouse = Db::name("githouse")->where(array("dep"=>$leader,"type"=>0))->find();
                if ($depHouse && $person['id']!=1){
                    $arr=array(array("id"=>$depHouse['id'],"gname"=>$depHouse['gname']));
                }
            }

        }

        $arr[]=array("id"=>1,"gname"=>"总部仓库");

        return $arr;
    }
    public function add(){

        $house = $this->getHouse();
        if ($this->request->isPost() && isset($_POST['sub'])) {
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            unset($post['riqi'],$post['shopList'],$post['sub']);
            //找到上级
            $leader = $this->getShangji($post['cid']);
            if (!$leader)$this->error("请联系所属公司管理员");
            $this->checkStore($shopList,$post['cid']);
            $post['sub']=$this->getSub($post['cid']);
            $pid = Db::name("purout")->insert($post,0,1);
            if (!$pid) {
                Db::rollback();
                $this->error("订单号重复");
            }
            foreach ($shopList as $k=>$v){
                $check=Db::name('purout_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'pur_id'=>$pid));
                if (!$check)break;
            }
            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{
                if ($post['status']==9){
                    //发送推送通知
                    $this->sendText("待审核通知","<div class=\"gray\">审核：".$this->getPublisher($post['publisher']).".有出库单需要审核，请前往处理</div>",$this->host."index/outpur/view/id/".$pid,$leader);

                }
                $this->setWork(Db::name("purout")->where(array("id"=>$pid))->find(),$post['status']);
                $this->success("添加成功");
            }

        }else{
            //获取当前仓库权限，并选择产品
            foreach ($house as $k=>$v) {
                $house[$k]['store']=$this->getCurStore($v['id']);
            }
            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }

            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);


            $this->view->assign("house",$house);
            $this->view->assign("username",$this->user['username']);
            if (count($house) > 1){
                $this->view->assign("st",0);
            }else{
                $this->view->assign("st",1);

            }
            $this->view->assign("bh",date("Ymd").substr(time(),6).random(4,1));
            //check_Department($this=2);

            return $this->view->fetch();
        }

    }

    protected function getCurStore($cid){
        if (!$cid)return 0;
        $wh['cid']=$cid;
        $wh['num']=array('gt',0);
        return Db::name('stock')->where($wh)->count();

    }
    protected function setWork($info,$status,$type=4){
        $id = $info["id"];

        if ($work = Db::name("workflow")->field("id")->where(array("tid"=>$id,"type"=>$type))->find()){
            Db::name("workflow")->where(array("id"=>$work['id']))->update(array("status"=>$status,"uptime"=>time()));
        }else{
            Db::name("workflow")->insert(array("tid"=>$id,"status"=>$status,"order_id"=>$info['order_id'],"type"=>$type,"inputtime"=>$info['createtime'],"uptime"=>time(), "userid"=>$this->user['userid']));

        }
        return true;

    }
    //销售出库
    public function getProduct3()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;

            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }

            if (isset($post['title']) && $post['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            //仓库开始
            $anywhere['cid']=$post['cid'];
            $anywhere['num']=array('gt',0);
            $stock=array_column(Db::name('stock')->where($anywhere)->field('shopid as id,cid,num')->select(),'id');

            if (!$stock)return json(array('list'=>[]));
            $where['id']=array('in',implode(',',$stock));

            //仓库结束
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();

            foreach($info as $k=>$v){
                if ($v['type']==2){
                    $info[$k]['type']="成品";
                }else{
                    $info[$k]['type']="半成品";
                }

                $info[$k]['storenum']=$this->getStore($v['id'],$post['cid']);
            }

            $result = array("list"=>$info);
            return $result;

        }
    }

    //入库获取产品
    public function getProduct2()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;
            if (isset($post['pid'])) {

                $where['type'] = $post['type'];
            }
            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }

            if (isset($post['title']) && $post['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            //仓库开始
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();
            foreach($info as $k=>$v){
                if ($v['type']==2){
                    $info[$k]['type']="成品";
                }else{
                    $info[$k]['type']="半成品";
                }

                $info[$k]['storenum']=$this->getStore($v['id'],$post['cid']);
            }

            $result = array("list"=>$info);
            return json($result);


        }
    }
    //获取产品信息
    public function getProduct()
    {
        if ($this->request->isAjax()){
            $where=[];
            $post = $_POST;
            if (isset($post['pid'])) {

                $where['type'] = $post['type'];
            }
            if (isset($post['pid']) && $post['pid'] > 0){
                $pid = intval($post['pid']);
                $where['classif']=$pid;
            }

            if (isset($post['title']) && $post['title']!=''){
                $title = $_POST['title'];
                $where['cname']=array('like',"%{$title}%");
            }
            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 6*($page-1);
            //仓库开始


            $anywhere['cid']=$post['cid'];
            $anywhere['num']=array('gt',0);
            $stock=array_column(Db::name('stock')->where($anywhere)->field('shopid as id,cid,num')->select(),'id');
            if (!$stock)return json(array('list'=>[]));
            $where['id']=array('in',implode(',',$stock));
            //仓库结束
            $info = Db::name('preproduct')->where($where)->limit($offset,6)->select();
            foreach($info as $k=>$v){
                if ($v['type']==2){
                    $info[$k]['type']="成品";
                }else{
                    $info[$k]['type']="半成品";
                }

                $info[$k]['storenum']=$this->getStore($v['id'],$post['cid']);
            }

            $result = array("list"=>$info);
            return json($result);


        }
    }
    function getCate1(){
        if (isset($_GET['type'])){
            $type = intval($_GET['type']);
            $where['type']=$type;
            $where['pid']=0;
            if ($type==2){
                $where['id']=array('neq',8);
            }
            $list = Db::name("halt_cate")->where($where)->field('id,pid,name')->select();
            $aid = $list[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$aid))->order("id asc")->select();
            $str='';
            foreach ($cate as $v){
                $str.='  <div class="cate_content_title">
                            <span class="h"></span><span>'.$v['name'].'</span><span class="h"></span>
                        </div>';
                $lists = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
                $str.=' <table cellspacing="0" cellpadding="0">
                            <tr>';
                foreach ($lists as $d){
                    $str.=' <td onclick="tdClick(this)" dataid="'.$d['id'].'">'.$d['name'].'</td>';
                }
                $str.='   </tr>
                        </table>';
            }
            return json(array('list'=>$list,'html'=>$str));
        }
    }
    //获取仓库
    protected function getHouse($url=''){
        $arr=[];
        $list = Db::name("githouse")->field('id,gname')->where(array("manger"=>$this->user['userid']))->select();
        if ($list){
            foreach ($list as $v){
                $arr[]=$v;
            }
        }
        //$this->auth->department='31';
        //检测当前所长分公司
        $depList = check_Department($this->auth->department,2);
        if ($depList){
            $ids= implode(',',array_column($depList,"id"));
            $where['dep']=array("in",$ids);
            $where['type']=0;


            if ($arr){
                $where['id']=array("notin",implode(',',array_column($arr,"id")));
            }
            $info = Db::name("githouse")->field('id,gname')->where($where)->select();
            foreach ($info as $v){
                $arr[]=$v;
            }
        }else{
                $arr[] = Db::name("githouse")->field('id,gname')->where(array("id"=>1))->find();
        }

        if (!$arr)$this->error("没有权限",$url);
        $tempArr=[];
        //删除重复
        foreach ($arr as $k=>$v){
            if (!in_array($v['id'],$tempArr)){
                array_push($tempArr,$v['id']);
            }else{
                unset($arr[$k]);
            }
        }
        return $arr;


    }

}